#coding=utf-8
from stutils import *
from stseries import *
from stutils import set_django_environ
set_django_environ()
from stdj.stock.models import Share,SMAPrice, SMAHsl, sma_periods
from stsettings import datadir

def sma2db(e, r):
    h = SMAHsl()
    h.exday = e 
    for i in range(len(sma_periods)):
        n = sma_periods[i]
        attr = 'ah%i'%n
        setattr(h, attr, r[i])
    h.save()
    
def sma2db_for_share(share, tocsv=True):
    eds = share.exday_set.order_by('date')
    
    #可能有这种情况：某一交易日没有换手率.eg:泛海建设(000046)1994-09-12
    start = 0
    hs = []
    for i in range(len(eds)):
        p = eds[i].price
        if not p.hsl:
            start = i + 1
            hs.append(None)
        else:
            hs.append(p.hsl)
            
    if start != 0: 
        print start
        eds = eds[start:]
        hs = hs[start:]
    #
    
    smas = []
    for pd in sma_periods:
        smas.append( sma(hs, pd) )
    
    
    #prepare data
    smas = zip(*smas)
    #to list
    for i in range(len(smas)):
        smas[i] = list(smas[i])
        
    for i in range(len(smas)):
        for j in range(len(smas[0])):
            if smas[i][j]:
                smas[i][j] = todec(smas[i][j], 2)    
                
    #data to db    
    for i in range(len(eds)):
        sma2db(eds[i], smas[i])
    
    #data to csv file
    if tocsv:
        head = ['日期', ]
        h2 = ['%i天'%i for i in sma_periods]
        head.extend(h2)
                
        data = []
        for i in range(len(eds)):
            d = [eds[i].date.isoformat(),]
            d.extend(smas[i])
            data.append(d)
            
        fn = datadir + '/tech/smav/%s.csv'%share.code
       
        data2csv(data, head, fn)
        
def sma2db_for_exday(e, tocsv=True):
    share = e.share
    r = []
    
    for n in sma_periods:
        ps = e.prenday_ps(n-1)
        ps.append(e.price)
        if len(ps) != n:
            break
        ends = [p.end for p in ps]
        r.append(average(ends))
        
    r = [todec(i,2)for i in r]
    
    n = len(sma_periods) - len(r)
    for i in range(n):
        r.append(None)
        
    #data 2 db
    sma2db(e, r)    
    
    #data 2 csv
    if tocsv:
        fn = datadir + '/tech/smap/%s.csv'%share.code
        f = open(fn, 'a')
        dl = [e.date.isoformat(),]
        
        r = [str(i) for i in r]
        dl.extend(r)
        s = ','.join(dl)
        
        f.write(s)
        f.write('\n')
    
def todaysma2db(share):
    e = share.exday_today()
    if not e:return
    sma2db_for_exday(e)
    
if __name__ == '__main__':
    for s in Share.objects.order_by('code').filter(code__gte='000046'):
        print s
        sma2db_for_share(s)
